﻿using Comm.Model;
using Comm.Model.Enums;
using Comm.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Comm.Web.Action
{
    /// <summary>
    /// UserManageCenter 的摘要说明
    /// </summary>
    public class UserManageCenter : BaseHander
    {
        public string Username { get; set; }
        public string Password { get; set; }
        BLL.UserServices _userService = new BLL.UserServices();
        BLL.UsersService blluser = new BLL.UsersService();
        BLL.OrdersService bllorder = new BLL.OrdersService();
        BLL.CheckAddressService blladdress = new BLL.CheckAddressService();
        BLL.MiBaoService bllmobao = new BLL.MiBaoService();
        BLL.Articel_WordsService bllword = new BLL.Articel_WordsService();
        public override void SonLoad()
        {
            string type = context.Request.Params["type"];
            switch (type) 
            {
                case "check":
                    GetCheck();
                    break;
                case "checkpwd":
                    GetCZPwd();
                    break;
                case "successInfo":
                    GetSuccessInfo();
                    break;
                case "MiBaoInfo":
                    GetMibaoInfo();
                    break;
                case "score":
                    GetScoreList();
                    break;
                case "del":
                    doaddressdel();
                    break;
                case "txt":
                    getCheckTXT();
                    break;
            }
        }

        public void GetCheck() 
        {
            Username = context.Request.Params["username"];
            Password = context.Request.Params["pwd"];
            Model.Users user;
            LoginResult res = _userService.CookieLogin(Username, Password, out user);
            switch (res)
            {
                case LoginResult.用户名不存在:
                case LoginResult.密码错误:
                    AjaxMsgHelper.AjaxMsg("err", "用户名或密码错误~~！");
                    return;
                case LoginResult.用户已被冻结:                   
                    AjaxMsgHelper.AjaxMsg("err", "用户状态异常~~！");
                    return;
                case LoginResult.登录成功:
                    AjaxMsgHelper.AjaxMsg("ok", "用户验证成功，请设置新密码！~~");
                    return;
  
            }
        }
        public void GetCZPwd() 
        {
            if (Request.Form["txtPwd"].ToString() != Request.Form["txtComPwd"].ToString()) 
            {
                AjaxMsgHelper.AjaxMsg("err","密码不一致");
                return;
            }
            Model.Users model = new Model.Users() 
            {
                 uLoginName=Request.Form["userId"],
                 uPwd = Request.Form["txtPwd"].Md5().ToUpper(),
                 uIsDel =false,
                 uId=UserNow.uId,
                 Phone=UserNow.Phone,
                 Mail=UserNow.Mail,
                 Address=UserNow.Address,
                 otherName=UserNow.otherName
                  
            };
            blluser.Update(model);
            string url ="../html/login.html";
            AjaxMsgHelper.AjaxMsg("ok","修改密码成功！~~",JsonHelper.Serialize(url));
        }

        public void GetSuccessInfo() 
        {
            Model.Users model = new Model.Users() 
            {
                 uId=UserNow.uId,
                 otherName = Request.Form["txtotherName"],
                 Address = Request.Form["txtAddress"],
                 Mail = Request.Form["txtEmail"],
                 Phone = Request.Form["txtPhone"],
                 uIsDel=false,
                 uLoginName=UserNow.uLoginName,
                 uPwd=UserNow.uPwd
            };
            blluser.Update(model);
            AjaxMsgHelper.AjaxMsg("ok","填写信息成功！~~");
        }

        public void GetMibaoInfo() 
        {
            int mibaoId1 = int.Parse(Request.Form["MiBao1"]);
            int mibaoId2 = int.Parse(Request.Form["MiBao2"]);
            int mibaoId3 = int.Parse(Request.Form["MiBao3"]);
            string question1 = Request.Form["Question1"];
            string question2 = Request.Form["Question2"];
            string question3 = Request.Form["Question3"];
            int[] Intdata = {mibaoId1,mibaoId2,mibaoId3 };
            string[] strdata = { question1, question2, question3 };
            bllmobao.Insert1(Intdata, UserNow.uId, strdata);
            AjaxMsgHelper.AjaxMsg("ok","密保设置成功！~~");
        }

        public void GetScoreList() 
        {
            IList<Orders> orders =  bllorder.GetOrderStatuIs0(UserNow.uId);
            AjaxMsgHelper.AjaxMsg("ok","数据加载成功！~~~",JsonHelper.Serialize(orders));
        }

        public void doaddressdel() 
        {
            blladdress.Delete(int.Parse(Request.Form["id"]));
            AjaxMsgHelper.AjaxMsg("ok","删除成功！~");
        }

        public void getCheckTXT() 
        {
            string Errorinfo = "";
            string strInfo = "";
            string _path = "";
            string _filepath="";
            try
            {
                if (context.Request.Form["btnDownWord"] != null)
                {
                    FileInfo[] finfo = null;
                    string _filename = UserNow.uLoginName;
                    _path = System.Web.HttpContext.Current.Server.MapPath("~/CodeTXT/" + _filename);//文件夹路径
                    if (Directory.Exists(_path))
                    {
                        string[] fn = Directory.GetFiles(_path);
                        DirectoryInfo dinfo = new DirectoryInfo(_path);
                        if (dinfo.Exists)
                        {
                            finfo = dinfo.GetFiles();
                        }
                    }
                    string encodeFileName = finfo[0].ToString();
                    _filepath = System.Web.HttpContext.Current.Server.MapPath("~/CodeTXT/" + _filename + "/" + encodeFileName);//文件路径
                    context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", encodeFileName));
                    context.Response.WriteFile(_filepath);//将文件输出到浏览器
                   // context.Response.End();//最好在一般处理程序中完成下载。
                }
                else {               
                HttpPostedFile file = context.Request.Files[0];
                string _name = file.FileName;
                if (_name.Split('.')[1] == "txt")
                {
                    string _fileName = UserNow.uLoginName;
                    _path = System.Web.HttpContext.Current.Server.MapPath("~/CodeTXT/" + _fileName);//文件夹路径
                    _filepath = System.Web.HttpContext.Current.Server.MapPath("~/CodeTXT/" + _fileName + "/" + file.FileName);//文件路径
                    if (Directory.Exists(_path))
                    {
                        Directory.Delete(_path, true);
                    }
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/CodeTXT/"+_fileName));
                    file.SaveAs(_filepath);
                    string msg = "";
                    using (StreamReader sr = new StreamReader(_filepath, System.Text.Encoding.GetEncoding("GB2312")))
                    {
                        msg = sr.ReadToEnd();
                        sr.Close();
                    }
                    msg = msg.Trim();
                    strInfo = msg.Replace("\r\n",",");
                    string[] words = msg.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);//分隔
                    int count = 0;
                    int sum = 0;
                    foreach (string word in words)
                    {
                        string[] codes = word.Split('=');
                        Articel_Words model = new Articel_Words();
                        if (bllword.CheckAllWord(codes[0]))
                        {
                            count++;
                           // strInfo += codes[0] + ",";
                        }
                        else 
                        {
                            model.WordPattern = codes[0];
                            if (codes[1] == "{BANNED}")
                            {
                                model.IsForbid = true;
                                model.IsMod = false;
                                model.ReplaceWord = "";
                            }
                            else if (codes[1] == "{MOD}")
                            {
                                model.IsMod = true;
                                model.IsForbid = false;
                                model.ReplaceWord = "";
                            }
                            else
                            {
                                model.IsMod = false;
                                model.IsForbid = false;
                                model.ReplaceWord = codes[1];
                            }
                            bllword.Insert(model);
                           // strInfo += codes[0] + ",";
                            sum++;
                        }  
                    }
                    if (context.Request.Form["btnLook"] != null)
                    {
                        Errorinfo = strInfo;
                        context.Response.Write("<script type='text/javascript'>window.parent.ShowInfo('true','" + Errorinfo + "',1);</script>");
                    }
                    else 
                    {
                        Errorinfo = "添加成功" + sum + "个，数据库中重复" + count + "个!~";
                        context.Response.Write("<script type='text/javascript'>window.parent.ShowInfo('true','" + Errorinfo + "',0);</script>");
                    }
                }
                else
                {
                    Errorinfo = "只能输入txt格式文件！";
                    context.Response.Write("<script type='text/javascript'>window.parent.ShowInfo('false','" + Errorinfo + "',0);</script>");
                }
              }
            }
            catch (Exception ex)
            {
                context.Response.Write("<script type='text/javascript'>window.parent.ShowInfo('false','" + ex.Message + "',0);</script>");
            }              
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}